<?php
namespace app\cgi\controller;

use app\common\validate\ApiAuth;
use think\Db;
use think\Cache;
use think\Config;
use think\Request;

class Base{
    public $ty_id = 0;
    public $userInfo = null;
    public $communityUser = null;
    public $request = null;
    public $curVersion = ''; //当前请求版本号
    public $isTestVersion = false; //是否是测试版本

    public function __construct(){
        new ApiAuth();
        $this->request = Request::instance();
        $this->setGlobalsSysVersion();
        $this->_initialize();
    }
    // 初始化
    protected function _initialize() {
    }
    public function responseError($msg='',$data='',$code=1){
        exit(json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data],JSON_UNESCAPED_UNICODE));
    }
    public function response($msg='',$data=''){
        exit(json_encode(['code'=>0,'msg'=>$msg,'data'=>$data],JSON_UNESCAPED_UNICODE));
    }
    public function _empty(){
        $this->responseError('URL错误');
    }
    /**
     * 权限校验
     */
    protected function auth(){
        if (!\Rbac::AccessCheckCgi($this->communityUser['id'])) {
            $this->responseError('没有权限');
        }
    }
    /*
     * 验证TOKEN是否合法
     * @access  public
     * @return  array() || (boolean)false
     */
    protected function authentication(){
        $token = $this->request->header('token');
        ( is_null($token) || '' === (string)$token ) &&  $this->responseError('缺少TOKEN');
        $openid = $this->request->header('openid');
        ( is_null($openid) || '' === (string)$openid ) &&  $this->responseError('缺少OPENID');
        if( self::hasCache('User_'.$openid) ) {
            $this->userInfo = self::getCache('User_'.$openid);
        } else {
            $this->userInfo = Db::name('user')->where(['openid'=>$openid])->field('id,nickname,headimgurl,realname,mobile,openid,unionid,token')->find();
            ( is_null($this->userInfo)  ) && $this->responseError('请登录');
            self::setCache('User_'.$openid,$this->userInfo);
        }
    }

    /*
     * 必须登录社区帐号*/
    protected function mustLogin(){
        $this->authentication();
        $account = $this->request->header('account');
        ( is_null($account) || '' === (string)$account ) && $this->responseError('请登录','',101);
        $this->communityUser = Db::name('community_user')->where(['openid'=>$this->userInfo['openid'],'account'=>$account,'isdelete'=>0,'ty_id'=>$this->ty_id])->field('id,realname,mobile,status,region')->find();
        is_null($this->communityUser) && $this->responseError('请重新登录','',101);
        1 !== (int)$this->communityUser['status'] && $this->responseError('帐号已被禁用','',101);
        $this->auth();
    }

    /*连接新的库*/
    protected function setGlobalsSysVersion(){
        $this->curVersion = $this->request->header('version','');
        $this->ty_id = $this->request->header('community',0);
        setGlobalsSysVersion($this->curVersion);
    }


    /* 数据缓存 */
    public static function setCache($key, $arr, $time = 86400) {
        Cache::set(Config::get('cache_fix') . $key, $arr, $time);
    }

    public static function getCache($key) {
        return Cache::get(Config::get('cache_fix') . $key);
    }

    public static function hasCache($key = '') {
        return Cache::has(Config::get('cache_fix') . $key);
    }
    public static function rmCache($key = '') {
        return Cache::rm(Config::get('cache_fix') . $key);
    }

    protected function getQrCode($path_url='',$d=''){
        vendor('weixin.code');
        $code = new \code();
        $weiXinConfig = Db::table('__WEIXIN__')->field('appid,appsecret,access_token,expires_time')->find();
        if( time() - $weiXinConfig['expires_time'] > 7000 ) {
            $token = $code->getToken($weiXinConfig['appid'],$weiXinConfig['appsecret']);
            Db::table('__WEIXIN__')->where(['id'=>1])->update(['access_token'=>$token,'expires_time'=>time()]);
        } else {
            $token = $weiXinConfig['access_token'];
        }
        if( '' == $d ) {
            //永久
            $ewm = $code->getWxCodeNew($token,$path_url);
        } else {
            //临时二维码
            $ewm = $code->getWxACodeUnlimit($token,$path_url,$d);
        }
        return $ewm ? uploadWeiXinQRCode($ewm) : '';
    }

    protected function getUserMenu($user_id){
        $nodes = \think\Loader::model('CommunityNode', 'logic')->getControllerMenu($user_id,'71');
        $menu = [];
        foreach ( $nodes as $k=>$v ){
            switch ( $v['name'] ) {
                case 'add':
                    $v['num'] = 0;
                    $v['url'] = '/pages/godown/add';
                    $v['ico'] = '/images/nva1.png';
                    break;
                case 'index':
                    $v['num'] = 0;
                    $v['url'] = '/pages/godown/index';
                    $v['ico'] = '/images/nva2.png';
                    break;
                case 'task':
                    $v['num'] = Db::name('case_godown')->alias('a')
                        ->join('__CASE_ALLOT__ d','d.id=a.allot_id','left')
                        ->where(['a.ty_id'=>$this->ty_id,'a.isdelete'=>0,'a.status'=>1,'a.state'=>2,'d.to_id'=>$this->communityUser['id']])->count();
                    $v['url'] = '/pages/godown/task';
                    $v['ico'] = '/images/nva3.png';
                    break;
                case 'wait':
                    $v['num'] = Db::name('case_godown')->alias('a')
                        ->where(['a.ty_id'=>$this->ty_id,'a.isdelete'=>0,'a.status'=>1,'a.state'=>1])
                        ->count();
                    $v['url'] = '/pages/godown/index?idx=0';
                    $v['ico'] = '/images/nva3.png';
                    break;
                case 'place':
                    $v['num'] = 0;
                    $v['url'] = '/pages/godown/index?idx=2';
                    $v['ico'] = '/images/nva4.png';
                    break;
            }
            if( !isset($v['url']) ) {
                continue;
            }
            9 < $v['num'] && $v['num'] = '*';
            $menu[] = $v;

        }
        return $menu;
    }


}
